<?php


namespace partner\core;


use Exception;
use WeChatPay\Builder;
use WeChatPay\Crypto\Rsa;
use WeChatPay\Util\PemUtil;

class BaseWechatPartner extends PartnerSdk
{
    protected $builder = null;
    protected $merchant_private_key_instance = null;
    protected $platform_public_key_instance = null;
    protected $platform_cert_serival = null;

    public function __construct(Container $app) 
    {
        parent::__construct($app);

        if (empty($this->app->params))
            throw new Exception("参数不能为空");

        // $this->setPlatformCertSerival();
        // $this->setPublicInstance();
        // $this->setPrivateInstance();
        // $this->setBuilder();

        if (isset($this->app->params['merchant_private_key_instance']))
            $this->merchant_private_key_instance = $this->app->params['merchant_private_key_instance'];
    }

    public function setPlatformCertSerival()
    {
        if (! isset($this->app->params['platform_cert']) ||
            ! file_exists($this->app->params['platform_cert']))
            throw new Exception('微信支付平台证书不存在');

        $this->platform_cert_serival = PemUtil::parseCertificateSerialNo($this->app->params['platform_cert']);
    }

    public function setPublicInstance() 
    {
        if (! isset($this->app->params['merchant_public_key']) ||
            ! file_exists($this->app->params['merchant_public_key']))
            throw new Exception("服务商平台公钥证书不存在");

        $this->platform_public_key_instance = Rsa::from($this->app->params['platform_public_key'], Rsa::KEY_TYPE_PUBLIC);
    }

    public function setPrivateInstance()
    {
        if (! isset($this->app->params['merchant_private_key']) ||
            ! file_exists($this->app->params['merchant_private_key']))
            throw new Exception("服务商商户私钥证书不存在");

        $this->merchant_private_key_instance = Rsa::from($this->app->params['merchant_private_key'], Rsa::KEY_TYPE_PRIVATE);
    }

    public function setBuilder()
    {
        $this->builder = Builder::factory([
            'mchid' => $this->app->params['merchant_id'],
            'serial' => $this->app->params['merchant_cert_serial'],
            'privateKey' => $this->merchant_private_key_instance,
            'certs' => [
                $this->platform_cert_serival => $this->platform_public_key_instance
            ],
        ]);
    }


}